<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils/index.js'
export default {
  name: 'Import',
  methods: {
    handleSuccess({ header, results }) {
      console.log(header, results)
    },
     transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }

      const res = results.map(item => {
        // item => {'姓名'：'小张'， '手机号': '13712345678'}
        const zhKeys = Object.keys(item)
        // zhKeys => ['姓名', '手机号']
        const obj = {}
        zhKeys.forEach(zhKey => {
          // zhKey => '姓名'
          const enKey = mapInfo[zhKey]
          // enKey => 'username'
          // 如果是日期格式，要做额外的处理
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            obj[enKey] = new Date(formatExcelDate(item[zhKey]))
          } else {
            obj[enKey] = item[zhKey]
          }
        })
        return obj
      })
      return res
    },
    async handleSuccess({ results, header }) {
      try {
        console.log('读出来的excel的内容是', results, header)
        // 1. 按照接口文档的要求，组装数据
        const data = this.transExcel(results, header)
        console.log(data)
        // 2. 调用接口，传递数据
        await importEmployee(data)
        this.$message.success('批量导入成功')
        // 3. 回跳到之前的页面
        this.$router.back()
      } catch (err) {
        this.$message.error(err.message)
      }
  }
}
}
</script>